package deom1;

public class MyList {
    static class ListNode {
        public int value;
        public ListNode next;
        ListNode(int value) {
            this.value = value;
        }
    }
    public ListNode head;

    //打印
    public void listPrint() {
        ListNode ret = head;
        while (ret.next != null) {
            System.out.print(ret.value+"  ");
            ret = ret.next;
        }
        System.out.println(ret.value+"  ");
    }

    //头插
    public void formerInsert(int data) {
        ListNode node = new ListNode(data);
        if (head == null) {
            head = node;
        } else {
            node.next = head;
            head = node;
        }
    }

    //尾插
    public void afterInsert(int data) {
        ListNode node = new ListNode(data);
        if(head == null) {
            head = node;
        } else {
            ListNode ret = head;
            while (ret.next != null) {
                ret = ret.next;
            }
            ret.next = node;
        }
    }

    //在 data 前面插入 val
    public void posFormerInsert(int data,int val) {
        ListNode node = new ListNode(val);
        ListNode ret = head;
        if(!containData(data)) {
            return;
        }
        if (ret.value == data) {
            node.next = head;
            head = node;
            return;
        }
        while (ret.next.value != data) {
            ret = ret.next;
        }
        node.next = ret.next;
        ret.next = node;
    }

    //在 data 后面插入 val
    public void posAfterInsert(int data,int val) {
        ListNode node = new ListNode(val);
        ListNode ret = head;
        if(!containData(data)) {
            return;
        }
        while (ret.value != data) {
            ret = ret.next;
            if(ret.next == null) {
                ret.next = node;
                return;
            }
        }
        node.next = ret.next.next;
        ret.next = node;
    }

    private boolean containData(int findData) {
        ListNode ret = head;
        while (ret.next != null) {
            if(ret.value == findData) {
                return true;
            }
            ret = ret.next;
        }
        if(ret.value == findData) {
            return true;
        }
        return false;
    }

    //删除
    public void removeData(int data) {
        if(!containData(data)) {
            return;
        }
        ListNode ret = head;
        if(head.value == data) {
            head = head.next;
            return;
        }
        while (ret.next.value != data) {
            ret = ret.next;
        }
        ret.next = ret.next.next;

    }
}
